package com.poetry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetry.domain.po.QuizList;
import com.poetry.exception.BasePage;
import com.poetry.exception.R;
import com.poetry.mapper.QuizListMapper;
import com.poetry.service.IQuizListService;
import com.poetry.util.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class QuizListServiceImpl extends ServiceImpl<QuizListMapper, QuizList>
        implements IQuizListService {

    @Override
    public R<String> addQuizList(Integer poemId) {
        QuizList quizList = new QuizList();
        quizList.setPoemId(poemId);
        quizList.setUserId(UserContext.getUserId());
        boolean isSuccess = this.save(quizList);
        if (!isSuccess) {
            return R.error("添加背诵清单失败");
        }
        return R.success(null, "添加背诵清单成功");
    }

    @Transactional
    @Override
    public R<String> deleteQuizList(Integer quizId) {
        boolean isSuccess = this.removeById(quizId);
        if (!isSuccess) {
            return R.error("移除失败");
        }
        return R.success(null, "移除成功");
    }

    @Override
    public R<List<QuizList>> getQuizList(BasePage basePage) {
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return R.error("用户未登录");
        }
        int pageNum = basePage.getPageNum();
        int pageSize = basePage.getPageSize();
        String condition = basePage.getCondition();
        Page<QuizList> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<QuizList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuizList::getUserId, userId);
        queryWrapper.eq(QuizList::getStatus, Boolean.parseBoolean(condition));
        queryWrapper.orderByAsc(QuizList::getUpdateTime);
        Page<QuizList> page = this.page(pageInfo, queryWrapper);
        if (page.getTotal() == 0) {
            return R.error("背诵列表为空");
        }
        return R.success("获取背诵列表成功", pageInfo.getRecords());
    }
}
